// src/screens/main/TranslateScreen.tsx
import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ScrollView,
  ActivityIndicator,
  Modal,
  FlatList,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import Clipboard from '@react-native-clipboard/clipboard';
import Toast from 'react-native-toast-message';
import aiService from '../../services/aiService';
import { Translation } from '../../types';

const languages = [
  { code: 'auto', name: '自动检测', flag: '🌐' },
  { code: 'zh-CN', name: '中文', flag: '🇨🇳' },
  { code: 'en', name: '英语', flag: '🇬🇧' },
  { code: 'ja', name: '日语', flag: '🇯🇵' },
  { code: 'ko', name: '韩语', flag: '🇰🇷' },
  { code: 'fr', name: '法语', flag: '🇫🇷' },
  { code: 'de', name: '德语', flag: '🇩🇪' },
  { code: 'es', name: '西班牙语', flag: '🇪🇸' },
  { code: 'ru', name: '俄语', flag: '🇷🇺' },
  { code: 'ar', name: '阿拉伯语', flag: '🇸🇦' },
  { code: 'pt', name: '葡萄牙语', flag: '🇵🇹' },
  { code: 'it', name: '意大利语', flag: '🇮🇹' },
];

const TranslateScreen: React.FC = () => {
  const [sourceText, setSourceText] = useState('');
  const [translatedText, setTranslatedText] = useState('');
  const [sourceLang, setSourceLang] = useState('auto');
  const [targetLang, setTargetLang] = useState('en');
  const [isLoading, setIsLoading] = useState(false);
  const [showSourcePicker, setShowSourcePicker] = useState(false);
  const [showTargetPicker, setShowTargetPicker] = useState(false);
  const [history, setHistory] = useState<Translation[]>([]);
  const [isFavorite, setIsFavorite] = useState(false);

  useEffect(() => {
    loadTranslationHistory();
  }, []);

  const loadTranslationHistory = async () => {
    try {
      // const historyData = await aiService.getTranslationHistory();
      // setHistory(historyData);
    } catch (error) {
      console.error('Load history error:', error);
    }
  };

  const handleTranslate = async () => {
    if (!sourceText.trim()) {
      Toast.show({
        type: 'error',
        text1: '请输入要翻译的文本',
      });
      return;
    }

    setIsLoading(true);
    try {
      const response = await aiService.translate({
        text: sourceText,
        sourceLang: sourceLang === 'auto' ? '' : sourceLang,
        targetLang,
      });

      setTranslatedText(response.translatedText);

      // 添加到历史记录
      const translation: Translation = {
        id: Date.now().toString(),
        sourceText,
        translatedText: response.translatedText,
        sourceLang: response.detectedLanguage || sourceLang,
        targetLang,
        timestamp: new Date(),
      };

      setHistory(prev => [translation, ...prev.slice(0, 9)]);

      Toast.show({
        type: 'success',
        text1: '翻译成功',
      });
    } catch (error: any) {
      Toast.show({
        type: 'error',
        text1: '翻译失败',
        text2: error.message || '请检查网络连接',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleSwapLanguages = () => {
    if (sourceLang !== 'auto') {
      const temp = sourceLang;
      setSourceLang(targetLang);
      setTargetLang(temp);

      if (translatedText) {
        const tempText = sourceText;
        setSourceText(translatedText);
        setTranslatedText(tempText);
      }
    }
  };

  const handleCopy = (text: string, type: 'source' | 'translated') => {
    Clipboard.setString(text);
    Toast.show({
      type: 'success',
      text1: '已复制到剪贴板',
      text2: type === 'source' ? '原文已复制' : '译文已复制',
    });
  };

  const handlePaste = async () => {
    const text = await Clipboard.getString();
    setSourceText(text);
  };

  const handleClear = () => {
    setSourceText('');
    setTranslatedText('');
    setIsFavorite(false);
  };

  const handleHistorySelect = (item: Translation) => {
    setSourceText(item.sourceText);
    setTranslatedText(item.translatedText);
    setSourceLang(item.sourceLang);
    setTargetLang(item.targetLang);
  };

  const toggleFavorite = () => {
    setIsFavorite(!isFavorite);
    Toast.show({
      type: 'success',
      text1: isFavorite ? '已取消收藏' : '已收藏',
    });
  };

  const renderLanguagePicker = (
    visible: boolean,
    onClose: () => void,
    onSelect: (lang: string) => void,
    selected: string,
    showAuto: boolean = false
  ) => (
    <Modal
      visible={visible}
      transparent
      animationType="slide"
      onRequestClose={onClose}
    >
      <TouchableOpacity
        style={styles.modalOverlay}
        activeOpacity={1}
        onPress={onClose}
      >
        <View style={styles.languagePickerContent}>
          <View style={styles.modalHeader}>
            <Text style={styles.modalTitle}>选择语言</Text>
            <TouchableOpacity onPress={onClose}>
              <Icon name="close" size={24} color="#666" />
            </TouchableOpacity>
          </View>

          <FlatList
            data={showAuto ? languages : languages.filter(l => l.code !== 'auto')}
            keyExtractor={item => item.code}
            renderItem={({ item }) => (
              <TouchableOpacity
                style={[
                  styles.languageOption,
                  selected === item.code && styles.languageOptionSelected
                ]}
                onPress={() => {
                  onSelect(item.code);
                  onClose();
                }}
              >
                <Text style={styles.languageFlag}>{item.flag}</Text>
                <Text style={[
                  styles.languageName,
                  selected === item.code && styles.languageNameSelected
                ]}>
                  {item.name}
                </Text>
                {selected === item.code && (
                  <Icon name="check" size={20} color="#667eea" />
                )}
              </TouchableOpacity>
            )}
          />
        </View>
      </TouchableOpacity>
    </Modal>
  );

  return (
    <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>
      {/* Language Selector */}
      <View style={styles.languageSelector}>
        <TouchableOpacity
          style={styles.langButton}
          onPress={() => setShowSourcePicker(true)}
        >
          <Text style={styles.langFlag}>
            {languages.find(l => l.code === sourceLang)?.flag}
          </Text>
          <Text style={styles.langButtonText}>
            {languages.find(l => l.code === sourceLang)?.name}
          </Text>
          <Icon name="arrow-drop-down" size={20} color="#667eea" />
        </TouchableOpacity>

        <TouchableOpacity
          onPress={handleSwapLanguages}
          style={styles.swapButton}
          disabled={sourceLang === 'auto'}
        >
          <Icon
            name="swap-horiz"
            size={24}
            color={sourceLang === 'auto' ? '#ccc' : '#667eea'}
          />
        </TouchableOpacity>

        <TouchableOpacity
          style={styles.langButton}
          onPress={() => setShowTargetPicker(true)}
        >
          <Text style={styles.langFlag}>
            {languages.find(l => l.code === targetLang)?.flag}
          </Text>
          <Text style={styles.langButtonText}>
            {languages.find(l => l.code === targetLang)?.name}
          </Text>
          <Icon name="arrow-drop-down" size={20} color="#667eea" />
        </TouchableOpacity>
      </View>

      {/* Source Text */}
      <View style={styles.textContainer}>
        <View style={styles.textHeader}>
          <Text style={styles.textLabel}>原文</Text>
          <View style={styles.textActions}>
            <TouchableOpacity onPress={handlePaste} style={styles.actionButton}>
              <Icon name="content-paste" size={20} color="#999" />
            </TouchableOpacity>
            {sourceText ? (
              <>
                <TouchableOpacity
                  onPress={() => handleCopy(sourceText, 'source')}
                  style={styles.actionButton}
                >
                  <Icon name="content-copy" size={20} color="#999" />
                </TouchableOpacity>
                <TouchableOpacity onPress={handleClear} style={styles.actionButton}>
                  <Icon name="clear" size={20} color="#999" />
                </TouchableOpacity>
              </>
            ) : null}
          </View>
        </View>

        <TextInput
          style={styles.textInput}
          placeholder="输入要翻译的文本..."
          placeholderTextColor="#999"
          value={sourceText}
          onChangeText={setSourceText}
          multiline
          numberOfLines={6}
          textAlignVertical="top"
        />

        <View style={styles.textFooter}>
          <Text style={styles.charCount}>{sourceText.length} / 5000</Text>
          {sourceText && (
            <TouchableOpacity style={styles.voiceButton}>
              <Icon name="volume-up" size={20} color="#667eea" />
            </TouchableOpacity>
          )}
        </View>
      </View>

      {/* Translate Button */}
      <TouchableOpacity
        style={[
          styles.translateButton,
          (!sourceText.trim() || isLoading) && styles.translateButtonDisabled
        ]}
        onPress={handleTranslate}
        disabled={isLoading || !sourceText.trim()}
      >
        {isLoading ? (
          <ActivityIndicator color="#fff" />
        ) : (
          <>
            <Icon name="translate" size={24} color="#fff" />
            <Text style={styles.translateButtonText}>翻译</Text>
          </>
        )}
      </TouchableOpacity>

      {/* Translated Text */}
      {translatedText ? (
        <View style={[styles.textContainer, styles.translatedContainer]}>
          <View style={styles.textHeader}>
            <Text style={styles.textLabel}>译文</Text>
            <View style={styles.textActions}>
              <TouchableOpacity
                onPress={() => handleCopy(translatedText, 'translated')}
                style={styles.actionButton}
              >
                <Icon name="content-copy" size={20} color="#999" />
              </TouchableOpacity>
              <TouchableOpacity
                onPress={toggleFavorite}
                style={styles.actionButton}
              >
                <Icon
                  name={isFavorite ? 'star' : 'star-border'}
                  size={20}
                  color={isFavorite ? '#ffd700' : '#999'}
                />
              </TouchableOpacity>
              <TouchableOpacity style={styles.actionButton}>
                <Icon name="share" size={20} color="#999" />
              </TouchableOpacity>
            </View>
          </View>

          <View style={styles.translatedTextContainer}>
            <Text style={styles.translatedText} selectable>
              {translatedText}
            </Text>
          </View>

          <View style={styles.textFooter}>
            <TouchableOpacity style={styles.voiceButton}>
              <Icon name="volume-up" size={20} color="#667eea" />
            </TouchableOpacity>
          </View>
        </View>
      ) : null}

      {/* Quick Actions */}
      <View style={styles.quickActions}>
        <TouchableOpacity style={styles.quickActionButton}>
          <Icon name="photo-camera" size={24} color="#667eea" />
          <Text style={styles.quickActionText}>拍照翻译</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.quickActionButton}>
          <Icon name="mic" size={24} color="#667eea" />
          <Text style={styles.quickActionText}>语音输入</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.quickActionButton}>
          <Icon name="history" size={24} color="#667eea" />
          <Text style={styles.quickActionText}>历史记录</Text>
        </TouchableOpacity>
      </View>

      {/* History */}
      {history.length > 0 && (
        <View style={styles.historySection}>
          <Text style={styles.historyTitle}>翻译历史</Text>
          {history.slice(0, 3).map((item) => (
            <TouchableOpacity
              key={item.id}
              style={styles.historyItem}
              onPress={() => handleHistorySelect(item)}
            >
              <View style={styles.historyContent}>
                <View style={styles.historyLanguages}>
                  <Text style={styles.historyLang}>
                    {languages.find(l => l.code === item.sourceLang)?.flag}
                  </Text>
                  <Icon name="arrow-forward" size={12} color="#999" />
                  <Text style={styles.historyLang}>
                    {languages.find(l => l.code === item.targetLang)?.flag}
                  </Text>
                </View>
                <Text style={styles.historySource} numberOfLines={1}>
                  {item.sourceText}
                </Text>
                <Text style={styles.historyTarget} numberOfLines={1}>
                  {item.translatedText}
                </Text>
              </View>
              <Text style={styles.historyTime}>
                {formatTime(item.timestamp)}
              </Text>
            </TouchableOpacity>
          ))}
        </View>
      )}

      {/* Language Pickers */}
      {renderLanguagePicker(
        showSourcePicker,
        () => setShowSourcePicker(false),
        setSourceLang,
        sourceLang,
        true
      )}
      {renderLanguagePicker(
        showTargetPicker,
        () => setShowTargetPicker(false),
        setTargetLang,
        targetLang,
        false
      )}
    </ScrollView>
  );
};

function formatTime(date: Date): string {
  const now = new Date();
  const diff = now.getTime() - new Date(date).getTime();
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);

  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;
  return new Date(date).toLocaleDateString('zh-CN');
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f9fa',
  },
  languageSelector: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 15,
    backgroundColor: '#fff',
    marginBottom: 1,
  },
  langButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 15,
    paddingVertical: 10,
    borderRadius: 25,
    backgroundColor: '#f0f0ff',
    flex: 0.42,
  },
  langFlag: {
    fontSize: 20,
    marginRight: 8,
  },
  langButtonText: {
    flex: 1,
    fontSize: 14,
    color: '#667eea',
    fontWeight: '600',
  },
  swapButton: {
    padding: 10,
  },
  textContainer: {
    backgroundColor: '#fff',
    padding: 15,
    marginBottom: 1,
  },
  translatedContainer: {
    backgroundColor: '#f0f8ff',
  },
  textHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
  },
  textLabel: {
    fontSize: 14,
    fontWeight: '600',
    color: '#333',
  },
  textActions: {
    flexDirection: 'row',
  },
  actionButton: {
    padding: 5,
    marginLeft: 10,
  },
  textInput: {
    fontSize: 16,
    color: '#333',
    minHeight: 120,
    textAlignVertical: 'top',
    lineHeight: 24,
  },
  textFooter: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 10,
  },
  charCount: {
    fontSize: 12,
    color: '#999',
  },
  voiceButton: {
    padding: 5,
  },
  translateButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#667eea',
    paddingVertical: 15,
    marginBottom: 1,
  },
  translateButtonDisabled: {
    backgroundColor: '#ccc',
  },
  translateButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
    marginLeft: 10,
  },
  translatedTextContainer: {
    backgroundColor: 'rgba(102, 126, 234, 0.05)',
    padding: 15,
    borderRadius: 10,
  },
  translatedText: {
    fontSize: 16,
    color: '#333',
    lineHeight: 24,
  },
  quickActions: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    paddingVertical: 20,
    backgroundColor: '#fff',
    marginTop: 10,
  },
  quickActionButton: {
    alignItems: 'center',
  },
  quickActionText: {
    fontSize: 12,
    color: '#666',
    marginTop: 5,
  },
  historySection: {
    padding: 15,
    backgroundColor: '#fff',
    marginTop: 10,
  },
  historyTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 15,
  },
  historyItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
    backgroundColor: '#f8f9fa',
    borderRadius: 10,
    marginBottom: 10,
  },
  historyContent: {
    flex: 1,
    marginRight: 10,
  },
  historyLanguages: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 5,
  },
  historyLang: {
    fontSize: 16,
    marginHorizontal: 3,
  },
  historySource: {
    fontSize: 14,
    color: '#666',
    marginBottom: 3,
  },
  historyTarget: {
    fontSize: 14,
    color: '#333',
    fontWeight: '600',
  },
  historyTime: {
    fontSize: 12,
    color: '#999',
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
  },
  languagePickerContent: {
    backgroundColor: '#fff',
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    maxHeight: '70%',
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
  },
  languageOption: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  languageOptionSelected: {
    backgroundColor: '#f0f0ff',
  },
  languageFlag: {
    fontSize: 16,
  },
  languageName: {
    flex: 1,
    fontSize: 16,
    color: '#333',
    marginLeft: 15,
  },
  languageNameSelected: {
    color: '#667eea',
    fontWeight: '600',
  },
});

export default TranslateScreen;